package com.zzh.myapplication.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;

import net.icarplus.car.R;
import net.icarplus.car.app.MyApplication;
import net.icarplus.car.fragment.MainFragment;
import net.icarplus.car.fragment.MineFragment;
import net.icarplus.car.fragment.OrderFragment;
import net.icarplus.car.manager.MainSelect;
import net.icarplus.car.tools.SPUtils;

public class MainActivity extends FragmentActivity implements RadioGroup.OnCheckedChangeListener, AMapLocationListener {

    public static final String TAG = "MainActivity";

    private android.support.v4.app.FragmentTransaction fragmentTransaction;

    private Fragment tabFragment;

    private Context context;

    private RadioGroup mTabMenu;

    public static MainSelect mainPage = MainSelect.MAIN;

    public static MainSelect preMainPage = null;

    private boolean isSwitch = true;

    private boolean jumpToLogin = false;

    public static boolean fromOrder = false;

    public AMapLocationClient mLocationClient = null;
    public AMapLocationClientOption mLocationOption = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        context = this;
        mainPage = MainSelect.MAIN;
        initView();
    }

    private void initView() {
        mTabMenu = (RadioGroup) findViewById(R.id.tab_menu);
        mTabMenu.setOnCheckedChangeListener(this);
        tabFragment = new MainFragment();
        switchFragment(tabFragment);

//        JSONObject jsons = new JSONObject();
//        try {
//            jsons.put("user_name", "13368973242");
//            jsons.put("user_password", Encrypt.get32MD5Str("123456"));
//            String encryptData = Base64.encodeToString(jsons.toString()
//                    .getBytes(), 0);
//            System.out.println("eeFSADFAFeefffe:" + encryptData );
//
//            OkHttpUtils.post().url("http://192.168.1.20:8005/mobile/index.php").addParams("act", "api").addParams("op", "login").addParams("data", encryptData).build().execute(new StringCallback() {
//                @Override
//                public void onError(Call call, Exception e) {
//                    System.out.println("error=========:"+ e );
//                }
//
//                @Override
//                public void onResponse(String response) {
//
//                }
//            });
//        } catch (JSONException e) {
//            System.out.println("eeeee:" + e);
//            e.printStackTrace();
//        }


        initMap();


    }

    private void switchFragment(Fragment fragment) {
        fragmentTransaction = getSupportFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.fragment_container, fragment);
        fragmentTransaction.commit();
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        if (isSwitch) {
            jumpToLogin = false;
            preMainPage = mainPage;
            switch (checkedId) {
                case R.id.rb_main:
                    mainPage = MainSelect.MAIN;
                    break;
                case R.id.rb_nearby:
                    mainPage = MainSelect.NEARBY;
                    break;
                case R.id.rb_order:
                    if (!SPUtils.getBoolean(this, "isLogin", false)) {
                        fromOrder = true;
                        jumpToLogin = true;
                    }
                    mainPage = MainSelect.ORDER;
                    break;
                case R.id.rb_mine:
                    if (!SPUtils.getBoolean(this, "isLogin", false)) {
                        fromOrder = false;
                        jumpToLogin = true;
                    }
                    mainPage = MainSelect.MINE;
                    break;
                default:
                    break;
            }
            if (jumpToLogin) {
                isSwitch = false;
                mainPage = preMainPage;
                initCheck();
                isSwitch = true;
                Intent intent = new Intent(context, LoginActivity.class);
                startActivityForResult(intent, 1, null);
            } else {
                setTabSelection(mainPage);
            }
        }
//        if (tabFragment != null) {
//            switchFragment(tabFragment);
//        }
    }

    public void setTabSelection(MainSelect index) {
        switch (index) {
            case MAIN:
                tabFragment = new MainFragment();
                break;
            case NEARBY:
                Intent intent = new Intent(MainActivity.this, NearbyActivity.class);
                startActivity(intent);
                break;
            case ORDER:
                tabFragment = new OrderFragment();
                break;
            case MINE:
                tabFragment = new MineFragment();
                break;
            default:
                tabFragment = null;
                break;

        }

        if (tabFragment != null) {
            switchFragment(tabFragment);
        }
    }

    public void initCheck() {
        switch (mainPage) {
            case MAIN:
                mTabMenu.check(R.id.rb_main);
                break;
            case NEARBY:
                mTabMenu.check(R.id.rb_nearby);
                break;
            case ORDER:
                mTabMenu.check(R.id.rb_order);
                break;
            case MINE:
                mTabMenu.check(R.id.rb_mine);
                break;
            default:
                break;
        }

    }

    @Override
    protected void onResume() {
        super.onResume();

        if (!SPUtils.getBoolean(this, "isLogin", false) && tabFragment != null && mainPage != null &&
                (mainPage == MainSelect.ORDER || mainPage == MainSelect.MINE) && preMainPage != null) {

            mainPage = preMainPage;
            switchFragment(tabFragment);
            isSwitch = false;
        } else if (tabFragment != null && mainPage != null &&
                (mainPage == MainSelect.NEARBY) && preMainPage != null) {
            mainPage = preMainPage;
            switchFragment(tabFragment);
            isSwitch = false;
        } else if (tabFragment != null && mainPage != null &&
                mainPage == MainSelect.MAIN && preMainPage != null) {
            mainPage = MainSelect.MAIN;
            switchFragment(tabFragment);
            isSwitch = false;
        } else {
            isSwitch = true;
        }
        initCheck();
        isSwitch = true;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (data == null) {
            return;
        }

        if (resultCode == SelectCityActivity.REQUESTCITY) {
            Bundle bundle = data.getBundleExtra("bundle");
            String currentCityName = bundle.getString("cityName");
            String currentCityCode = bundle.getString("cityCode");
            System.out.println("namemaanaa:" + currentCityName);

            if (this.tabFragment != null) {
                if (this.tabFragment.getClass() == MainFragment.class) {

                    ((MainFragment) this.tabFragment).setCurrentCity(currentCityName);

                }
                return;
            }

        }
        if (requestCode == LoginActivity.REQUESTFORLOGIN) {
            if (!SPUtils.getBoolean(getApplicationContext(), "isLogin", false)) {
                if (preMainPage != null) {
                    mainPage = preMainPage;
                    initCheck();
                }
            }
        }
    }

    public long time;

    public void onBackPressed() {
        // TODO Auto-generated method stub
        // super.onBackPressed();
        if (System.currentTimeMillis() - time < 2000) {
            finish();
        } else {
            time = System.currentTimeMillis();
            Toast.makeText(this, "再按一次", Toast.LENGTH_SHORT).show();
        }
        // ActivityManager manager = (ActivityManager) getSystemService("");
    }

    private String endStringWithEllip(String content, int length) {
        if (content.length() > length) {
            StringBuilder sb = new StringBuilder(content.substring(0, length));
            sb.append("...");
            return sb.toString();
        } else {
            return content;
        }
    }

    private void initMap() {
//        if (aMap == null) {
//            aMap = mapView.getMap();
//            mUiSettings = aMap.getUiSettings();
//        }
        mLocationClient = new AMapLocationClient(getApplicationContext());
        mLocationClient.setLocationListener(this);
        mLocationOption = new AMapLocationClientOption();
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        mLocationOption.setNeedAddress(true);
        mLocationOption.setOnceLocation(true);
        mLocationOption.setMockEnable(false);
//        MyLocationStyle myLocationStyle = new MyLocationStyle();
//        myLocationStyle.myLocationIcon(BitmapDescriptorFactory
//                .fromResource(R.mipmap.dibiao));// 设置小蓝点的图标
//        myLocationStyle.strokeColor(Color.argb(0, 0, 0, 0));// 设置圆形的边框颜色
//        myLocationStyle.radiusFillColor(Color.argb(0, 0, 0, 0));// 设置圆形的填充颜色
//        myLocationStyle.strokeWidth(0f);// 设置圆形的边框粗细
//        aMap.setMyLocationStyle(myLocationStyle);
//        aMap.setMyLocationRotateAngle(180);
//        aMap.setLocationSource(this);// 设置定位监听
//        mUiSettings.setMyLocationButtonEnabled(false); // 是否显示默认的定位按钮
//        aMap.setMyLocationEnabled(true);// 是否可触发定位并显示定位层
//        mUiSettings.setScaleControlsEnabled(true);// 设置地图默认的比例尺是否显示
//        mUiSettings.setZoomControlsEnabled(false);
        mLocationClient.setLocationOption(mLocationOption);
        mLocationClient.startLocation();
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (aMapLocation != null) {
            MyApplication.aAMapLocation = aMapLocation;

            System.out.println("address::" + MyApplication.aAMapLocation.getProvince() + " " + MyApplication.aAMapLocation.getCity() + " " + MyApplication.aAMapLocation.getDistrict());

            String curCity = MyApplication.aAMapLocation.getCity();
            String curDistrict = MyApplication.aAMapLocation.getDistrict();
            if (!curCity.contains("市")) {
                ((MainFragment) this.tabFragment).setCurrentCity(curDistrict);
            } else {
                ((MainFragment) this.tabFragment).setCurrentCity(curCity);
            }
        }
    }
}
